<template>
  <div class="page">
    <div class="left">
      <div class="left-actions">
        <el-button type="primary" @click="openCreateType">新建类型</el-button>
        <el-button @click="loadTypes">刷新类型</el-button>
      </div>
      <el-menu :default-active="currentType" @select="onSelectType" class="type-menu">
        <el-menu-item v-for="t in types" :key="t.code" :index="t.code">{{ t.name }}（{{ t.code }}）</el-menu-item>
      </el-menu>
    </div>
    <div class="right">
      <div class="right-actions">
        <div class="type-title">当前类型：{{ currentType }}</div>
        <el-button type="primary" :disabled="!currentType" @click="openCreateItem">新建字典项</el-button>
      </div>
      <div class="table-area">
        <el-table :data="items" style="width:100%">
          <el-table-column prop="code" label="编码" min-width="160" />
          <el-table-column prop="name" label="名称" min-width="180" />
          <el-table-column prop="enabled" label="启用" width="100">
            <template #default="{ row }">
              <el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '启用' : '停用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="order_index" label="排序" width="100" />
          <el-table-column fixed="right" label="操作" width="180">
            <template #default="{ row }">
              <el-button size="small" @click="openEditItem(row)">修改</el-button>
              <el-popconfirm title="确定删除该字典项？" @confirm="removeItem(row)">
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog v-model="showTypeDialog" :title="typeDialogTitle" width="520px" destroy-on-close>
      <el-form :model="typeForm" label-width="100px">
        <el-form-item label="类型编码"><el-input v-model="typeForm.code" :disabled="editingType" /></el-form-item>
        <el-form-item label="类型名称"><el-input v-model="typeForm.name" /></el-form-item>
        <el-form-item label="描述"><el-input v-model="typeForm.description" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showTypeDialog=false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submitType">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showItemDialog" :title="itemDialogTitle" width="520px" destroy-on-close>
      <el-form :model="itemForm" label-width="100px">
        <el-form-item label="编码"><el-input v-model="itemForm.code" /></el-form-item>
        <el-form-item label="名称"><el-input v-model="itemForm.name" /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="itemForm.enabled" /></el-form-item>
        <el-form-item label="排序"><el-input v-model.number="itemForm.order_index" type="number" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showItemDialog=false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submitItem">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { api } from '../../api/client'

type DictType = { code: string; name: string; description?: string }
type DictItem = { id: string; type_code: string; code: string; name: string; enabled: boolean; order_index: number }

const types = ref<DictType[]>([])
const items = ref<DictItem[]>([])
const currentType = ref<string>('')
const saving = ref(false)

async function loadTypes() {
  const { data } = await api.get('/dictionaries/types')
  types.value = data
  if (!currentType.value && types.value.length) {
    currentType.value = types.value[0].code
    await loadItems()
  }
}

async function loadItems() {
  if (!currentType.value) { items.value = []; return }
  const { data } = await api.get('/dictionaries/items', { params: { type_code: currentType.value } })
  items.value = data
}

function onSelectType(code: string) {
  currentType.value = code
  loadItems()
}

// type dialog
const showTypeDialog = ref(false)
const typeDialogTitle = ref('新建类型')
const editingType = ref(false)
const typeForm = reactive<DictType>({ code: '', name: '', description: '' })
function openCreateType() {
  typeDialogTitle.value = '新建类型'
  editingType.value = false
  Object.assign(typeForm, { code: '', name: '', description: '' })
  showTypeDialog.value = true
}
async function submitType() {
  saving.value = true
  try {
    if (editingType.value) {
      await api.put(`/dictionaries/types/${typeForm.code}`, { name: typeForm.name, description: typeForm.description })
    } else {
      await api.post('/dictionaries/types', { ...typeForm })
    }
    showTypeDialog.value = false
    await loadTypes()
  } finally { saving.value = false }
}

// item dialog
const showItemDialog = ref(false)
const itemDialogTitle = ref('新建字典项')
const editingItemId = ref<string | null>(null)
const itemForm = reactive<DictItem>({ id: '', type_code: '', code: '', name: '', enabled: true, order_index: 0 })
function openCreateItem() {
  if (!currentType.value) return
  itemDialogTitle.value = '新建字典项'
  editingItemId.value = null
  Object.assign(itemForm, { id: '', type_code: currentType.value, code: '', name: '', enabled: true, order_index: 0 })
  showItemDialog.value = true
}
function openEditItem(row: DictItem) {
  itemDialogTitle.value = '修改字典项'
  editingItemId.value = row.id
  Object.assign(itemForm, row)
  showItemDialog.value = true
}
async function submitItem() {
  saving.value = true
  try {
    if (editingItemId.value) {
      await api.put(`/dictionaries/items/${editingItemId.value}`, { code: itemForm.code, name: itemForm.name, enabled: itemForm.enabled, order_index: itemForm.order_index })
    } else {
      await api.post('/dictionaries/items', { type_code: itemForm.type_code, code: itemForm.code, name: itemForm.name, enabled: itemForm.enabled, order_index: itemForm.order_index })
    }
    showItemDialog.value = false
    await loadItems()
  } finally { saving.value = false }
}
async function removeItem(row: DictItem) {
  await api.delete(`/dictionaries/items/${row.id}`)
  await loadItems()
}

onMounted(async () => {
  if (!currentType.value) currentType.value = 'activity_type'
  await loadItems()
  await loadTypes()
})
</script>

<style scoped>
.page { height: 100%; display: flex; }
.left { width: 280px; border-right: 1px solid var(--border-soft, #e9edf3); padding: 8px; box-sizing: border-box; display: flex; flex-direction: column; }
.left-actions { display: flex; gap: 8px; margin-bottom: 8px; }
.type-menu { flex: 1; overflow: auto; }
.right { flex: 1; display: flex; flex-direction: column; padding: 8px; box-sizing: border-box; }
.right-actions { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
.type-title { color: var(--text-muted, #6b7280); }
.table-area { flex: 1; min-height: 0; }
.table-area :deep(.el-table__body-wrapper) { height: 100%; overflow: auto; }
</style>
